package com.miraeasset.toxml;
import java.util.List;
import java.util.Map;

public class ListConsistOfMapGenerator implements IXmlGenerator {
	 
	public String getParentTag() {
		return parentTag;
	}
	public void setParentTag(String parentTag) {
		this.parentTag = parentTag;
	}
	public String getSectionTag() {
		return sectionTag;
	}
	public void setSectionTag(String sectionTag) {
		this.sectionTag = sectionTag;
	}
	public String toXml(){
		return generate();
	}
	
	public void setData(Object data) {
		this.dataList = (List<Map<Object, Object>>)data;
	}
	
	private final String xmlHeader = "<?xml version='1.0' encoding='utf-8'?>";
	private String parentTag;
	private String sectionTag;
	private List<Map<Object, Object>> dataList;
	
	private String generate(){
		StringBuffer buf = new StringBuffer(xmlHeader);
		
		if(parentTag != null) buf.append(getStartTag(parentTag));
		
		for(Map<Object, Object> mapItem : dataList)
			buf.append(mapToXml(mapItem));
		
		if(parentTag != null) buf.append(getEndTag(parentTag));
		
		return buf.toString();
	}
	private String mapToXml(Map<Object, Object> map)
	{
		StringBuffer buf = new StringBuffer();
		if(sectionTag != null) buf.append(getStartTag(sectionTag));
		for(final Map.Entry<Object, Object> entry : map.entrySet()){
			buf.append(generateTag(entry.getKey().toString(), entry.getValue().toString()));
		}
		if(sectionTag != null) buf.append(getEndTag(sectionTag));
		return buf.toString();
	}
	private String getStartTag(String tagName)
	{
		return "<" +tagName.toUpperCase() + ">";
	}
	private String getEndTag(String tagName)
	{
		return "</" + tagName.toUpperCase() + ">";
	}
	private String generateTag(String tagName, String tagValue)
	{
		return getStartTag(tagName) + tagValue + getEndTag(tagName);
	}
}